package com.sgb.kjwl.view.ui.fragment.self;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtPackersManageAlbumBinding;
import com.sgb.kjwl.di.self.DaggerSelfFragComponent;
import com.sgb.kjwl.di.self.SelfFragModule;
import com.sgb.kjwl.model.entity.self.ResponseList;
import com.sgb.kjwl.model.entity.self.SelfTeamAlbumEntity;
import com.sgb.kjwl.model.entity.self.SelfTeamIntroduceEntity;
import com.sgb.kjwl.model.entity.self.TeamUploadAlbumEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfPackersManageActivity;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfTeamAlbumEditActivity;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfTeamIntroduceActivity;
import com.sgb.kjwl.view.ui.adapter.self.packers.SelfTeamAlbumAdapter;
import com.sgb.kjwl.viewmodel.self.packers.FragAlbumModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import static android.app.Activity.RESULT_OK;

public class FragAlbumFragment extends AppLazyFragment {

    @Inject
    FragAlbumModel viewModel;
    private AtPackersManageAlbumBinding binding;
    private SelfTeamAlbumAdapter photoAdapter;

    private ArrayList<String> urls;
    private ArrayList<File> fileList;
    private ArrayList<String> netPhotoList;
    private TeamUploadAlbumEntity teamUploadAlbumEntity;
    private List<TeamUploadAlbumEntity.UrlsBean> uploadImgList;
    private int currentImgNum = 0;
    private int imgTotal = 0;
    private List<SelfTeamAlbumEntity> photoList;

    public static FragAlbumFragment newInstance() {
        FragAlbumFragment fragment = new FragAlbumFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerSelfFragComponent.builder()
                .appComponent(appComponent)
                .selfFragModule(new SelfFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.at_packers_manage_album, container, false);
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
        photoAdapter = new SelfTeamAlbumAdapter(getActivity(), manager);
        binding.listView.setLayoutManager(manager);
        binding.listView.setAdapter(photoAdapter);
        binding.listView.setPullRefreshEnabled(false);
        binding.listView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                viewModel.requestTeamAlbumData(true);
            }
        });

        binding.tvAdd.setOnClickListener(this);
        binding.teamPublish.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_add:
                if (photoAdapter.getUrls().size() > 0) {
                    SelfTeamAlbumEditActivity.start(getActivity(), photoList);
                } else {
                    MToast.showToast(getActivity(), "暂无照片");
                }
                break;
            case R.id.team_publish:
                viewModel.getTeamIntroduce();
                break;
        }
    }

    public void updateIntroduce(SelfTeamIntroduceEntity data) {
        if (data != null){
            PictureSelector.create(getActivity())
                    .openGallery(PictureMimeType.ofImage())
                    .loadImageEngine(GlideEngine.createGlideEngine())
                    .theme(R.style.picture_default_style)
                    .maxSelectNum(9)//判断还能选多少张图片
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }else {
            optTmpState();
        }
    }

    @Override
    protected void onLazyLoad() {
        fileList = new ArrayList<>();
        urls = new ArrayList<>();
        netPhotoList = new ArrayList<>();
        uploadImgList = new ArrayList<>();

        //获取网络照片
        viewModel.requestTeamAlbumData(false);
    }

    public void getPhotoData(ResponseList<List<SelfTeamAlbumEntity>> list, boolean isLoadMore) {
        binding.layoutNullTeam.setVisibility(View.GONE);
        if (isLoadMore) {
            binding.listView.loadMoreComplete();
            if (list.getList() != null && list.getList().size() != 0) {
                photoList.addAll(list.getList());
                netPhotoList.clear();
                for (SelfTeamAlbumEntity entity : list.getList()) {
                    netPhotoList.add(entity.getUrl());
                }
                photoAdapter.setNetImgList(netPhotoList);
            }
        } else {
            if (list.getList() != null && list.getList().size() != 0){
                binding.linTopLabel.setVisibility(View.VISIBLE);
                binding.tvListTotal.setText("工队相册 " + list.getTotalRow() + " 张");
                binding.tvAdd.setText("编辑工队相册");
                photoList = list.getList();
                netPhotoList.clear();
                for (SelfTeamAlbumEntity entity : list.getList()) {
                    netPhotoList.add(entity.getUrl());
                }
                photoAdapter.setNetImgList(netPhotoList);
                binding.listView.refreshComplete();
                binding.listView.setLoadingMoreEnabled(true);
            }else {
                binding.layoutNullTeam.setVisibility(View.VISIBLE);
            }
        }
    }

    public void pictureSelectorResult(List<LocalMedia> selectList){
            fileList.clear();
            urls.clear();
            for (LocalMedia localMedia : selectList) {
                File file = new File(localMedia.getRealPath());
                fileList.add(file);
                urls.add(localMedia.getRealPath());
            }
            photoAdapter.setDatas(selectList, urls);
            photoAdapter.setFileList(fileList);
            imgTotal = fileList.size();
            viewModel.uploadMutiFileModel(fileList.get(currentImgNum), currentImgNum + 1, imgTotal);
    }

    //单个上传
    public void uploadImgSuccess(String url) {
        TeamUploadAlbumEntity.UrlsBean entity = new TeamUploadAlbumEntity.UrlsBean();
        entity.setUrl(url);
        uploadImgList.add(entity);
        if (currentImgNum + 1 == imgTotal) {
            uploadSuccess(uploadImgList);
        } else {
            currentImgNum++;
            viewModel.uploadMutiFileModel(fileList.get(currentImgNum), currentImgNum + 1, imgTotal);
        }
    }

    public void uploadSuccess(List<TeamUploadAlbumEntity.UrlsBean> list) {
        teamUploadAlbumEntity = new TeamUploadAlbumEntity();
        teamUploadAlbumEntity.setUrls(list);
        viewModel.savePhotoData(teamUploadAlbumEntity);
        Log.v("uploadFile", "success--all--");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String event) {
        if ("save_photo_data".equals(event)) {
            //删除后刷新列表
            if (null != photoAdapter.getUrls()) {
                photoAdapter.getUrls().clear();
            }
            viewModel.requestTeamAlbumData(false);
        }
    }

    private void optTmpState() {
        new CommonDialog(getActivity()).builder().setPositiveButton("去完善").setNegativeButton("取消")
                .setTitle("请先完善工队信息")
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        Intent intent = new Intent(getActivity(), SelfTeamIntroduceActivity.class);
                        startActivityForResult(intent, FragIntroduceFragment.REQUEST_EDIT_CODE);
                    }

                    @Override
                    public void onLeftClick() {

                    }
                }).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == FragIntroduceFragment.REQUEST_EDIT_CODE){
                ((SelfPackersManageActivity) getActivity()).refreshTeamData();
            }
        }
    }
}
